//
//  UIButton+SLKit.m
//  SLKit
//
//  Created by chengdonglu on 2021/10/30.
//  Copyright © 2021 S_LINE. All rights reserved.
//

#import "UIButton+SLKit.h"

#import <objc/runtime.h>

#import "NSObject+SLSafe.h"

#define TOUCHUPINSIDE_KEY @(UIControlEventTouchUpInside)

static char gEventDictKey;

@implementation UIButton (SLKit)

- (void)addTouchUpInsideEvent:(SLButtonEvent)event {
    [self removeTarget:self action:@selector(touchUpInsideEvent) forControlEvents:UIControlEventTouchUpInside];
    [self.eventDict setObject:event forKey:TOUCHUPINSIDE_KEY];
    [self addTarget:self action:@selector(touchUpInsideEvent) forControlEvents:UIControlEventTouchUpInside];

}

- (void)touchUpInsideEvent {
    
    if ([self.eventDict.allKeys containsObject:@(UIControlEventTouchUpInside)]) {
        SLButtonEvent block = [self.eventDict sl_objectForKey:TOUCHUPINSIDE_KEY];
        if (block) {
            block();
        }
    }
}

- (NSMutableDictionary<NSNumber *,SLButtonEvent> *)eventDict {
    NSMutableDictionary<NSNumber *, SLButtonEvent> *eventDict = objc_getAssociatedObject(self, &gEventDictKey);
    if (!eventDict) {
        eventDict = [[NSMutableDictionary alloc] init];
        objc_setAssociatedObject(self, &gEventDictKey, eventDict, OBJC_ASSOCIATION_RETAIN);
    }
    return eventDict;
}

- (void)setEventDict:(NSMutableDictionary<NSNumber *,SLButtonEvent> *)eventDict {
    objc_setAssociatedObject(self, &gEventDictKey, eventDict, OBJC_ASSOCIATION_RETAIN);
}

@end
